# editcarddialog.py
# this is a dialog to allow the user to edit the word types.

from PyQt4 import QtGui, QtCore
from wordtype import *

class WordTypeDialog(QtGui.QDialog):
    def __init__(self, vocab, parent = None):
        QtGui.QDialog.__init__(self, parent)
        self.setWindowTitle('Edit Word Types')
        
        self.vocab = vocab
        
        self.tabPane = QtGui.QTabWidget(self)
        self.tabs = {}
        self.newWordTypeTabs = {}
        for wordtype in self.vocab.wordtypes:
            #page = QtGui.QScrollArea()
            self.tabs[wordtype] = WordTypeEditPane(self.vocab.wordtypes[wordtype])
            #page.setWidget(self.tabs[wordtype])
            #self.tabPane.addTab(page, self.vocab.wordtypes[wordtype].name)
            self.tabPane.addTab(self.tabs[wordtype], self.vocab.wordtypes[wordtype].name)
        
        self.mainLayout = QtGui.QVBoxLayout()
        self.mainLayout.addWidget(self.tabPane)
        self.newWordType = QtGui.QPushButton('New Word Type')
        self.newWordType.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        self.mainLayout.addWidget(self.newWordType)
        self.buttonPane = QtGui.QWidget()
        self.buttonPaneLayout = QtGui.QHBoxLayout()
        self.okButton = QtGui.QPushButton('OK')
        self.cancelButton = QtGui.QPushButton('Cancel')
        self.buttonPaneLayout.addWidget(self.okButton)
        self.buttonPaneLayout.addWidget(self.cancelButton)
        self.buttonPaneLayout.addStretch()
        self.buttonPane.setLayout(self.buttonPaneLayout)
        self.mainLayout.addWidget(self.buttonPane)
        self.setLayout(self.mainLayout)
        
        self.connect(self.okButton, QtCore.SIGNAL('clicked()'), self.ok)
        self.connect(self.cancelButton, QtCore.SIGNAL('clicked()'), self.cancel)
        self.connect(self.newWordType, QtCore.SIGNAL('clicked()'), self.makeWordType)
    
    def ok(self):
        # first add the newly created wordtypes in
        for newWordTypeName in self.newWordTypeTabs:
            if not self.newWordTypeTabs[newWordTypeName].forDeletion:
                self.vocab.wordtypes[newWordTypeName] = self.newWordTypeTabs[newWordTypeName].wordtype
                self.tabs[newWordTypeName] = self.newWordTypeTabs[newWordTypeName]
        # next delete all the deleted word types
        for wordtype in self.tabs:
            if self.tabs[wordtype].forDeletion:
                del self.vocab.wordtypes[wordtype]
                for card in self.vocab.cards:
                   if card.wordType.name == wordtype:
                       card.wordType = self.vocab.wordtypes[self.tabs[wordtype].changeTo]
            else: # for all the wordtypes that aren't being deleted...
                # update the updated fields
                for i in range(0, len(self.tabs[wordtype].fields)):
                    fieldME = self.tabs[wordtype].fields[i]
                    if not fieldME.deleteMe:
                        self.vocab.wordtypes[wordtype].fields[i].label = str(fieldME.labelEdit.text())
                        self.vocab.wordtypes[wordtype].fields[i].position = fieldPositionLabel[str(fieldME.selectPosition.currentText())]
                        self.vocab.wordtypes[wordtype].fields[i].show = fieldShowLabel[str(fieldME.selectShow.currentText())]
                        self.vocab.wordtypes[wordtype].fields[i].font = str(fieldME.selectFont.currentText())
                # delete the deleted fields
                for i in range(0, len(self.tabs[wordtype].fields)):
                    fieldME = self.tabs[wordtype].fields[i]
                    if fieldME.deleteMe:
                        self.vocab.wordtypes[wordtype].deleteField(fieldME.field.name)
                # add the new fields
                for i in range(0, len(self.tabs[wordtype].newFields)):
                    fieldME = self.tabs[wordtype].newFields[i]
                    if not fieldME.deleteMe:
                        fieldME.field.label = str(fieldME.labelEdit.text())
                        fieldME.field.position = fieldPositionLabel[str(fieldME.selectPosition.currentText())]
                        fieldME.field.show = fieldShowLabel[str(fieldME.selectShow.currentText())]
                        fieldME.field.font = str(fieldME.selectFont.currentText())
                        self.vocab.wordtypes[wordtype].fields.append(fieldME.field)
        self.close()
        self.vocab.changed = True
        self.vocab.refreshAllCards()
    
    def cancel(self):
        self.close()
    
    def makeWordType(self):
        (wordTypeName, ok) = QtGui.QInputDialog.getText(self, 'New Word Type Name', 'Enter a name for the word type')
        if ok:
            if wordTypeName in self.vocab.wordtypes.keys():
                QtGui.QMessageBox.information(self, 'Word type already exists', "%s already exists as a word type in this vocab" % (wordTypeName))
            else:
                if len(self.vocab.wordtypes) < 2:
                    self.tabs[self.tabs.keys()[0]].deleteWordtypeButton.setEnabled(True)
                fields = []
                # there are 4 compulsory fields in a wordtype, should be found as the first four fields in the first wordtype
                if len(self.vocab.wordtypes):
                    firstWordType = self.vocab.wordtypes.keys()[0]
                    for i in range(0,4):
                        fields.append(self.vocab.wordtypes[firstWordType].fields[i].copy())
                else:
                    compulsory = ['chapter', 'difficulty', 'english', 'foreign']
                    for fieldName in compulsory:
                        fields.append(Field(self.wordtype.vocab, fieldName, fieldName, self.wordtype.vocab.fonts.keys()[0], FieldPosition.LEFT, FieldShow.ALWAYS))
                page = QtGui.QScrollArea()
                self.newWordTypeTabs[wordTypeName] = WordTypeEditPane(WordType(self.vocab, wordTypeName, fields))
                page.setWidget(self.newWordTypeTabs[wordTypeName])
                self.tabPane.addTab(page, wordTypeName)
                self.tabPane.setCurrentIndex(self.tabPane.count() - 1)
                
class WordTypeEditPane(QtGui.QWidget):
    def __init__(self, wordtype, parent = None):
        QtGui.QWidget.__init__(self, parent)
        
        self.wordtype = wordtype
        self.pageLayout = QtGui.QVBoxLayout()
        self.setLayout(self.pageLayout)
        
        self.deleteWordtypeLayout = QtGui.QHBoxLayout()
        self.deleteWordtypeButton = QtGui.QPushButton('Delete this wordtype')
        if len(self.wordtype.vocab.wordtypes) < 2:
            self.deleteWordtypeButton.setEnabled(False)
        self.deleteWordtypeLabel = QtGui.QLabel('and change any ' + self.wordtype.name + ' cards into:')
        self.changeWordsTo = QtGui.QComboBox()
        items = self.wordtype.vocab.wordtypes.keys()
        assert items.count(self.wordtype.name) <= 1
        if items.count(self.wordtype.name) > 0:
            items.remove(self.wordtype.name)
        self.changeWordsTo.addItems(items)
        
        self.deleteWordtypeLayout.addWidget(self.deleteWordtypeButton)
        self.deleteWordtypeLayout.addWidget(self.deleteWordtypeLabel)
        self.deleteWordtypeLayout.addWidget(self.changeWordsTo)
        self.pageLayout.addLayout(self.deleteWordtypeLayout)
        
        self.forDeletion = False
        self.changeTo = None
        
        self.fields = []
        self.newFields = []
        self.fieldEditGrid = QtGui.QGridLayout()
        self.fieldEditGrid.addWidget(QtGui.QLabel('Field Name'), 0, 1)
        self.fieldEditGrid.addWidget(QtGui.QLabel('Label'), 0, 2)
        self.fieldEditGrid.addWidget(QtGui.QLabel('Position'), 0, 3)
        self.fieldEditGrid.addWidget(QtGui.QLabel('Show'), 0, 4)
        self.fieldEditGrid.addWidget(QtGui.QLabel('Font'), 0, 5)
        for i in range(0, len(self.wordtype.fields)):
            self.fields.append(FieldMetaEdit(self.wordtype.fields[i], self.fieldEditGrid, self))
        self.pageLayout.addLayout(self.fieldEditGrid)
        self.pageLayout.addStretch()
        
        self.newField = QtGui.QPushButton('New Field')
        self.newField.setSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        self.pageLayout.addWidget(self.newField)
        
        #self.setSizePolicy(QtGui.QSizePolicy.Minimum, QtGui.QSizePolicy.Minimum)
        
        self.connect(self.newField, QtCore.SIGNAL('clicked()'), self.makeNewField)
        self.connect(self.deleteWordtypeButton, QtCore.SIGNAL('clicked()'), self.deleteWordtype)
    
    def deleteWordtype(self):
        reply = QtGui.QMessageBox.question(
            self, "Delete %s?" % (self.wordtype.name),
            "Are you sure you want to delete the %s word type and change all %s cards into %s cards?" % (self.wordtype.name, self.wordtype.name, self.changeWordsTo.currentText()),
            QtGui.QMessageBox.Yes,
            QtGui.QMessageBox.No)
        if reply == QtGui.QMessageBox.Yes:
            self.forDeletion = True
            self.changeTo = str(self.changeWordsTo.currentText())
            # tabPane.removeTab(tabPane.indexOf(page))
            self.parent().parent().parent().parent().removeTab(self.parent().parent().parent().parent().indexOf(self.parent().parent()))
    
    def makeNewField(self):
        (fieldName, ok) = QtGui.QInputDialog.getText(self, 'New Field Name', 'Enter a name for the field')
        if ok:
            newFieldME = FieldMetaEdit(
                Field(
                    self.wordtype.vocab,fieldName,fieldName,
                    self.wordtype.vocab.fonts.keys()[0],
                    FieldPosition.LEFT, FieldShow.ALWAYS),
                self.fieldEditGrid,
                self)
            self.newFields.append(newFieldME)
        
